<?php

namespace App\Exceptions;

use Illuminate\Auth\AuthenticationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\ValidationException;
use Ninex\Lib\Exceptions\LibExceptionHandler;
use Stancl\Tenancy\Exceptions\TenantCouldNotBeIdentifiedOnDomainException;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Throwable;

class Handler extends LibExceptionHandler
{
    /**
     * A list of exception types with their corresponding custom log levels.
     *
     * @var array<class-string<\Throwable>, \Psr\Log\LogLevel::*>
     */
    protected $levels = [
        //
    ];

    /**
     * A list of the exception types that are not reported.
     *
     * @var array<int, class-string<\Throwable>>
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed to the session on validation exceptions.
     *
     * @var array<int, string>
     */
    protected $dontFlash = [
        'current_password',
        'password',
        'password_confirmation',
    ];

    /**
     * Register the exception handling callbacks for the application.
     */
    public function register(): void
    {
        $this->reportable(function (Throwable $e) {
            //

        });
    }
    public function render($request, $exception)
    {
        $this->code = $exception->getCode() ?? 201;
        $msg = $exception->getMessage();
        $httpStatus = 500;
        if ($exception instanceof AccessDeniedHttpException) {
            $this->code = 403;
            $httpStatus = 403;
        } elseif ($exception instanceof AuthenticationException) {
            $this->code = 403;
            $httpStatus = 403;
        } elseif ($exception instanceof NotFoundHttpException) {
            $this->code = 500;
            $httpStatus = 404;
        } elseif ($exception instanceof MethodNotAllowedHttpException) {
            $this->code = 500;
            $httpStatus = 405;
        } elseif ($exception instanceof ValidationException) {
            $this->code = 422;
            $httpStatus = 200;
            $msg = $exception->validator->messages()->first();
        } elseif ($exception instanceof BusinessException) {
            $httpStatus = 200;
            $this->code = 400;
        } elseif ($exception instanceof HttpException) {
            $this->code = 500;
        } elseif ($exception instanceof ModelNotFoundException) {
            $this->code = 600;
        } elseif ($exception instanceof QueryException) {
            $this->code = 600;
        } elseif ($exception instanceof \ReflectionException) {
            $this->code = 700;
        } elseif ($exception instanceof \RuntimeException) {
            $this->code = 800;
        } elseif ($exception instanceof \ErrorException) {
            $this->code = 900;
        } else {
            $this->code = 900;
        }
        $result = [
            'code' => $this->code,
            'msg' => $this->msg[$this->code] ?? $msg,
            'data' => []
        ];
        $error_context = $this->convertExceptionToArray($exception);
        if (config('app.debug')) {
            $result['error_msg'] = $msg;
            $result['error_line'] = $exception->getFile() . ':' . $exception->getLine();
            $result['error_context'] = $error_context;
        }
        //出现非200的错误，记录日志
        if (isset($this->levels[$this->code]) && $httpStatus !== 200) {
            Log::log($this->levels[$this->code], $result['msg'], $error_context);
        }
        return response()->json($result, $httpStatus)->setEncodingOptions(JSON_UNESCAPED_UNICODE);
    }
}
